#include "ecc.c"
#include "aes.c"

#include "ssl.h"

void hex_print(uint8_t *buf, size_t len)
{
    unsigned i;
    for(i=0; i<len-1; i++){
        printf("%02X", (unsigned)buf[i]);
    }
    printf("%02X\n", (unsigned)buf[i]);
}

int gen_random_bytes(void *buf, size_t len)
{
	FILE *fp = fopen("/dev/urandom", "rb");
	if(fp == 0){
		perror("fopen");
		return -1;
	}

    if(fread(buf, len, 1, fp) != 1){
        sprintf((char *)stderr, "Failed to get random bytes.\n");
		return -1;
    }
	fclose(fp);
	return len;
}

int ecc_gen_key(EccPoint *pub_key, uint8_t pri_key[NUM_ECC_DIGITS]){
	//return -1 if generated failed
	if(gen_random_bytes((char *)pri_key, NUM_ECC_DIGITS) < 0){
		return -1;
	};
	
	//return 1 if generated successfully
	if(ecc_make_key(pub_key, pri_key, pri_key) == 0){
		return -1;
	};
	
	return 0;
}

int aes_set_secret(uint8_t *secret, uint8_t *w){
	//generated the aes expansion key
	key_expansion(secret, w);
	return 0;
}

int aes_ctr_cipher(uint8_t *buf, size_t len, uint8_t *w, uint8_t *random){
	uint8_t key[16];
	struct {
		uint8_t prefix[12];
		uint32_t count;
	}k;
	//init aes input data
	memcpy(&k, random, 16);
	k.count = 0;
	//start encrypt
	unsigned long int i;
	for(i=0;i<len;i++){
		//generated key steam even 16 rounds
		if(i%16==0){
			cipher((uint8_t *)&k, key, w);
			k.count++;
		}
		//xor buf and key steam
		buf[i%16] ^= key[i%16];
	}

	return 0;
}
